package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class ApUserLoginServiceImpl implements ApUserLoginService {

    @Autowired
    ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDTO dto) {
        String phone = dto.getPhone();
        String password = dto.getPassword();
        // 检验是否手机和密码
        if (StringUtils.isNotBlank(phone)&&StringUtils.isNotBlank(password)){
            // 查询数据库是否存在用户
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery()
                    .eq(ApUser::getPhone, phone));
            if (apUser==null){
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户数据不存在");

            }
            // 密码加密
            String asHexPwd = DigestUtils.md5DigestAsHex((password + apUser.getSalt()).getBytes());
            // 密码输入是否正确
            if (!asHexPwd.equals(apUser.getPassword())){
                CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码输入错误");
            }
            // 颁发token
            String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
            // 封装map
            Map map = new HashMap<>();
            map.put("token",token);
            apUser.setSalt("");
            apUser.setPassword("");
            map.put("user",apUser);
            return ResponseResult.okResult(map);
        }else {
            // 没有手机和密码则查询是否有手机id
            if (dto.getEquipmentId()==null){
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"设备id不能为空");
            }
            // 直接封装token id设置为0
            String token = AppJwtUtil.getToken(0L);
            // 封装map
            Map map = new HashMap<>();
            map.put("token",token);
            return ResponseResult.okResult(map);
        }
    }
}
